<template>
  <div class="book-detail-area">
    <div class="middle">
      <bread-crumb class="bread-crumb-padding" :list="breadCrumb"></bread-crumb>
      <div class="flx-row-bw">
        <div class="left-area">
          <div class="box" v-if="id != -1" style="position: relative">
            <Spin :withIcon="true" v-if="loading"></Spin>
            <div class="flx-row-bw info-area">
              <div class="box-left-area">
                <div class="flx-row-s-c" style="margin-bottom: 5px">
                  <h2>{{ name }}</h2>
                  <i v-if="isTop == 1">推荐</i>
                </div>
                <span>{{ meaning }}</span>
              </div>
              <div class="box-right-area">
                <div class="flx-row-s-c">
                  <a
                    :href="item.href"
                    :class="{ 'mg-r-14': index < websiteList.length - 1 }"
                    v-for="(item, index) in websiteList"
                    :key="index"
                    >{{ item.name }}</a
                  >
                </div>
                <div class="flx-row-s-c" style="margin-top: 10px">
                  分享
                  <div class="share-icon share1"></div>
                  <div class="share-icon share2"></div>
                  <div class="share-icon share3"></div>
                </div>
              </div>
            </div>
            <div class="flx-row-s-s">
              <div class="flx-col-s-c w-p-100 time-area">
                <span class="name">原注册日期</span>
                <span class="time">{{
                  registrantTime == null ? "" : registrantTime
                }}</span>
              </div>
              <div class="flx-col-s-c w-p-100 time-area">
                <span class="name">删除日期</span>
                <span class="time">{{ serverDeleteTime }}</span>
              </div>
              <div class="flx-col-s-c w-p-100 time-area">
                <span class="name">剩余时间</span>
                <span class="time"
                  ><span v-if="day > 0">{{ day }}天</span
                  ><span>{{ hour }}时</span><span>{{ min }}分</span
                  ><span v-if="day <= 0">{{ sec }}秒</span></span
                >
              </div>
            </div>
            <h3 class="title-h3" style="margin: 24px 0 20px 30px">
              请选择预订通道
            </h3>
            <div style="position: relative">
              <Spin :withIcon="true" v-if="formLoading"></Spin>
              <RadioGroup class="w-p-100" v-model="channelSelect">
                <table class="table-area">
                  <thead>
                    <tr>
                      <th>
                        <div class="line-style">通道名称</div>
                      </th>
                      <th>
                        <div class="line-style">成功率</div>
                      </th>
                      <th>
                        <div class="line-style">起拍价格</div>
                      </th>
                      <th>
                        <div class="line-style">预订保证金</div>
                      </th>
                      <th>
                        <div class="line-style">注册商数量</div>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="(item, index) in channelList"
                      :key="index"
                      :class="[(index + 1) % 2 != 0 ? 'lc-f' : 'lc-F9FAFB']"
                    >
                      <td>
                        <div class="line-style-left">
                          <Radio
                            :label="item.id"
                            class="flx-row-s-c"
                            style="display: flex"
                          >
                            <span
                              class="strong-f f-ell-sin"
                              :title="item.channelName"
                              >{{ item.channelName }}</span
                            >
                          </Radio>
                        </div>
                      </td>
                      <td>
                        <div class="line-style">
                          <span class="normal-f f-ell-sin"
                            >{{ item.successRate }}%</span
                          >
                        </div>
                      </td>
                      <td>
                        <div class="line-style">
                          <span class="normal-f f-ell-sin"
                            >￥{{ item.bookPrice }}元</span
                          >
                        </div>
                      </td>
                      <td>
                        <div class="line-style">
                          <span class="normal-f f-ell-sin"
                            >￥{{ item.bookBond }}元</span
                          >
                        </div>
                      </td>
                      <td>
                        <div class="line-style">
                          <span class="normal-f f-ell-sin"
                            >{{ item.registrantCount }}个</span
                          >
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </RadioGroup>
              <div class="flx-row-s-c check-area">
                <Checkbox v-model="agree"></Checkbox>
                我同意
                <span @click="seriveRuleModelShow = true"
                  >《{{ seriveRuleTitle }}》</span
                >
                并已阅读
                <span @click="ruleModelShow = true">《{{ ruleTitle }}》</span>
              </div>
              <!-- <div class="flx-row-s-c check-area">
                <Checkbox v-model="agree"></Checkbox>
                我同意
                <span>《抢注预订服务协议》</span>
                并已阅读
                <span>《抢注预订须知》</span>
              </div> -->
              <div class="submit-button" @click="showPayModalShow">
                立即预订
              </div>
            </div>
          </div>
          <Empty-State
            style="background-color: #fff"
            v-else
            content="未找到此域名！"
          ></Empty-State>
          <div class="box flx-col-c-c bottom-box">
            <h2 class="flow-chart-title">抢注预订流程图</h2>
            <span class="flow-name">单人预订</span>
            <div class="long-arrow"></div>
            <div class="flx-row-s-s">
              <template v-for="(item, index) in flowList">
                <div
                  :key="'o' + index"
                  class="flow-item"
                  :class="{ 'flow-item-strong': index == 0 }"
                  :style="{
                    backgroundImage: `url(${require('_a/images/' +
                      item.image +
                      '@2x.png')})`,
                  }"
                >
                  {{ item.name }}
                </div>
                <div
                  :key="'os' + index"
                  v-if="index < flowList.length - 1"
                  class="arrow-item flow-name"
                  :style="{
                    backgroundImage: `url(${require('_a/images/' +
                      item.arrow +
                      '@2x.png')})`,
                  }"
                >
                  {{ item.arrowText }}
                </div>
              </template>
            </div>
          </div>
        </div>
        <div class="right-area">
          <h3 class="title-h3" style="margin-left: 0">抢注预订须知</h3>
          <p v-for="(item, index) in tips" :key="index">{{ item }}</p>
        </div>
      </div>
    </div>
    <pay-modal
      :show.sync="payModalShow"
      :sumPayable="sumPayable"
      :orderNo="orderNo"
      @start-pay="startPay"
    >
      <div class="flx-row-bw-c">
        <span class="f-16 c-d2"
          >域名预订：<span class="f-18 f-w-600 c-o">{{ name }}</span></span
        >
        <span class="f-16 c-d2"
          >预订保证金：<span class="f-18 f-w-600 c-r"
            >￥{{ bondMoney }}</span
          ></span
        >
        <span class="f-16 c-d2"
          >应付金额：<span class="f-18 f-w-600 c-gr"
            >￥{{ sumPayable }}</span
          ></span
        >
      </div>
    </pay-modal>
    <order-success-modal
      :show.sync="orderSuccessModalShow"
    ></order-success-modal>
    <to-login-modal
      :show.sync="loginModelShow"
      @toLogin="toLogin"
    ></to-login-modal>
    <rule-modal
      :show.sync="ruleModelShow"
      :content="ruleContent"
      :title="ruleTitle"
    ></rule-modal>
    <rule-modal
      :show.sync="seriveRuleModelShow"
      :content="seriveRuleContent"
      :title="seriveRuleTitle"
    ></rule-modal>
  </div>
</template>

<script>
import { bookingChannel } from "@/utils/publicData";
import { getDNDetail } from "@/api/data";
import { showtime } from "@/utils/format";
import { createBookingOrder, getOrderStatus } from "@/api/user";
import axios from "axios";
const bottomInfoUrl =
  process.env.NODE_ENV === "development"
    ? config2.bottomInfoUrl.dev
    : config2.bottomInfoUrl.pro;
const webScoketUrl =
  process.env.NODE_ENV === "development"
    ? config2.webScoketUrl.dev
    : config2.webScoketUrl.pro;
export default {
  name: "VipBookdetail",
  components: {
    payModal: () => import("_c/modal/payModal/payModal.vue"),
    toLoginModal: () => import("_c/modal/toLoginModal/toLoginModal.vue"),
    ruleModal: () => import("_c/modal/ruleModal/ruleModal.vue"),
    orderSuccessModal: () =>
      import("_c/modal/orderSuccessModal/orderSuccessModal.vue"),
  },
  data() {
    return {
      loading: false,
      formLoading: false,
      ruleModelShow: false,
      ruleContent: "",
      ruleTitle: "",
      seriveRuleModelShow: false,
      seriveRuleContent: "",
      seriveRuleTitle: "",
      breadCrumb: [
        { name: "域名预订", to: "/dnbooking" },
        { name: "预订详情", to: "/bookDetail" },
      ],
      tips: [
        "1、当您提交抢注预订订单并交纳保证金后，本站会为您预订域名;",
        "2、如有多人预订同一个域名(且预订价格相同)，预订成功后则需要进行竞价，竞价结束价高者得;",
        "3、如您预订的域名只有您一人预订，那么预订成功后，您直接得标，无需竞价;",
        "4、如果预订失败，系统自动退还预订保证金(可以提现);",
        "5、如果预订成功后您只需要付相应的预订价格即可，无需另付其它费用(抢注预订价格，包含了域名的注册费用，预订成功后大部分域名可直接解析使用);",
        "6、已经预订的域名无法取消预订;",
        "7、预订结果:部分平台在域名预订失败后的30个工作日，会继续尝试着为用户继续预订该域名，或修正错误处理为失败的域名，成功后修正域名预订状态并且扣除相应款项，本站会相应修改预订结果和扣款;",
        "8、域名得标后，系统将自动从您的可用余额中扣除相应款项。如余额不足，请在72小时内补齐;若未补齐，视为您已经违约，平台将有权对域名进行拍卖或变卖。",
        "9、如您违约，平台有权做以下操作:扣除违约域名对应的保证金，违约账号将被限制使用易名旗下所有服务，与违约账号关联的账号将被限制使用预订服务。违约域名可由平台进行处理，用于补偿您的违约对平台造成的损失。",
        "10、预订的域名不得用于制作钓鱼诈骗色情等非法网站，发现一律封锁域名，封锁帐户，费用不退，并且将违法帐户信息上报公安部门，后果自负，谢谢合作!",
        "11，由我司通道抢注成功的域名将在您支付尾款后7天内交割给您;由于注册局的转移限制，由合作商通道抢注成功的域名将于域名竞价结衷后的60天〔含60天]之内交割给您，请您谅解。",
      ],
      websiteList: [
        {
          name: "SEO信息",
          href: "#",
        },
        {
          name: "whois",
          href: "#",
        },
        {
          name: "百度",
          href: "#",
        },
        {
          name: "爱站",
          href: "#",
        },
        {
          name: "谷歌",
          href: "#",
        },
      ],
      timeList: [
        {
          name: "原注册日期",
          time: "1998-02-03",
        },
        {
          name: "删除日期",
          time: "2021-02-03",
        },
        {
          name: "剩余时间",
          time: "1天20时",
        },
      ],
      flowList: [
        {
          name: "抢注预订",
          image: "flow1",
          arrow: "arrow1",
          arrowText: "",
        },
        {
          name: "抢注成功",
          image: "flow2",
          arrow: "arrow2",
          arrowText: "多人预订",
        },
        {
          name: "竞价",
          image: "flow3",
          arrow: "arrow2",
          arrowText: "得标",
        },
        {
          name: "支付尾款",
          image: "flow4",
          arrow: "arrow2",
          arrowText: "",
        },
        {
          name: "交接域名",
          image: "flow5",
          arrow: "arrow2",
          arrowText: "",
        },
      ],
      channelList: [],
      id: null,
      name: "",
      meaning: "",
      registrantTime: "",
      serverDeleteTime: "",
      isTop: 0,
      day: "",
      hour: "",
      min: "",
      sec: "",
      leftTimeIntervel: null,

      // 交易信息
      bondMoney: "",
      sumPayable: "",
      leftMoney: "",
      orderNo: "",

      // 表单数据
      channelSelect: null,
      agree: false,
      // 弹框展示
      payModalShow: false,
      orderSuccessModalShow: false,
      loginModelShow: false,

      // 获取支付数据
      isStart: true,
      getTimeOutTimeOut: null,
    };
  },
  created() {
    this.getChannel();
    this.getRule();
    let id = this.$route.query.id;
    if (id == null || id == "" || isNaN(id) || id <= 0) {
      this.id = -1;
    } else {
      this.id = id;
    }
    this.getDn();
    let temp = this.$storage.getToLoginData();
    if (temp) {
      this.agree = temp.agree;
      this.channelSelect = temp.channelSelect;
      this.$storage.setToLoginData("");
    }
  },
  methods: {
    // 获取协议
    getRule() {
      axios(`${bottomInfoUrl}/biddingBookingRules.json`).then((res) => {
        if (res != null && res.data != null) {
          this.ruleTitle = res.data.title;
          this.ruleContent = res.data.content;
        }
      });
      axios(`${bottomInfoUrl}/biddingBookingSeriveRules.json`).then((res) => {
        if (res != null && res.data != null) {
          this.seriveRuleTitle = res.data.title;
          this.seriveRuleContent = res.data.content;
        }
      });
    },
    // 获取通道
    async getChannel() {
      let res = await bookingChannel();
      this.channelList = res;
    },
    // 获取域名信息
    async getDn() {
      this.loading = true;
      let res = await getDNDetail(this.id);
      if (res.code == 200) {
        this.name = res.data.name;
        this.meaning = res.data.meaning;
        this.registrantTime = res.data.registrantTime;
        this.serverDeleteTime = res.data.serverDeleteTime;
        this.isTop = res.data.isTop;
        this.leftTimeIntervel = setInterval(() => {
          let time = showtime(res.data.serverDeleteTime);
          this.day = time.day;
          this.hour = time.hour;
          this.min = time.min;
          this.sec = time.sec;
        }, 1000);
      } else {
        this.id = -1;
      }
      this.loading = false;
    },
    // 显示选择付款弹窗
    async showPayModalShow() {
      if (!this.$token.get()) {
        this.loginModelShow = true;
        return;
      }
      if (this.channelSelect == null || this.channelSelect == "") {
        this.$Message.warning("请选择预订通道");
        return;
      }
      if (!this.agree) {
        this.$Message.warning(
          "请同意《抢注预订服务协议》并已阅读《抢注预订须知》"
        );
        return;
      }
      this.formLoading = true;
      let data = {
        channelId: this.channelSelect,
        domainBookingId: this.id,
      };
      let res = await createBookingOrder(data);
      if (res.code == 200) {
        this.payModalShow = true;
        this.bondMoney = res.data.bond;
        this.sumPayable = res.data.amount;
        this.leftMoney = res.data.balance;
        this.$store.commit("setBalance", res.data.balance);
        this.orderNo = res.data.orderNo;
      }
      this.formLoading = false;
    },
    // 开始付款
    startPay() {
      if (this.isStart) {
        this.isStart = false;
        this.startSocket();
      }
    },
    // 获取订单状态
    // async getOrderStatus() {
    //   let res = await getOrderStatus(this.orderNo);
    //   if(res.code == 200) {
    //     console.log(res.data);
    //     this.payModalShow = false
    //     this.orderSuccessModalShow = true
    //   } else {
    //     this.getTimeOutTimeOut = setTimeout(() => {
    //       this.getOrderStatus();
    //     }, 2000);
    //   }
    // }
    // webScoket发送消息
    sendMessage(txt) {
      this.webSocket.send(txt);
    },
    // webScoket异常重连
    resetConnect() {
      this.connectCount = this.connectCount || 0;
      if (!this.webSocketInterval) {
        // console.log("开始webSocket重连");
        this.webSocketResetInterval = setInterval(() => {
          this.connectCount += 1;
          if (this.connectCount <= 5) {
            this.startSocket();
            this.webSocketResetInterval &&
              clearInterval(this.webSocketResetInterval);
          }
        }, 1000);
      }
    },
    // 开启webScoket
    startSocket() {
      this.messageTotal = 0;
      this.webSocket = new WebSocket(
        `${webScoketUrl}/web/webSocket/pay/${this.orderNo}/${this.$token.get()}`
      );
      // 接收消息事件
      this.webSocket.onmessage = (e) => {
        console.log(e);
        if (e.data === "open:suc") {
          this.sendMessage("start");
          this.heartInterval = setInterval(() => {
            if (this.messageTotal === 10) {
              this.sendMessage("heart");
              this.messageTotal = 0;
            }
            this.messageTotal += 1;
          }, 1000);
        }
        if (e.data.indexOf("msg:") != -1) {
          let message = e.data.split("msg:")[1];
          this.messageTotal = 0;
          let info = JSON.parse(message);
          if (info != null) {
            if (info.result == "true") {
              this.sendMessage("stop");
              this.payModalShow = false;
              this.orderSuccessModalShow = true;
              this.heartInterval && clearInterval(this.heartInterval);
            }
          }
        }
        if (e.data.indexOf("rec:stop") != -1) {
          this.webSocket.close();
        }
      };
      // 关闭事件
      // this.webSocket.onclose = () => {
      //   this.resetConnect();
      // };
      // 连接失败事件
      this.webSocket.onerror = () => {
        this.resetConnect();
      };
    },
    // 去登陆
    toLogin() {
      this.$storage.setToLoginData({
        channelSelect: this.channelSelect,
        agree: this.agree,
      });
      window.location.href = "/login";
    },
  },
  beforeDestroy() {
    clearInterval(this.leftTimeIntervel);
    // clearTimeout(this.getTimeOutTimeOut);
    if (!this.isStart) {
      if (this.webSocket) this.sendMessage("stop");
      this.heartInterval && clearInterval(this.heartInterval);
      this.webSocketResetInterval && clearInterval(this.webSocketResetInterval);
    }
  },
};
</script>

<style lang="scss" scoped>
.book-detail-area {
  background-color: #f7f7f7;
  padding-bottom: 20px;

  .left-area {
    width: 750px;
    .box {
      background: #ffffff;
      border: 1px solid #eaeaea;

      .info-area {
        padding: 20px 30px;

        .box-left-area {
          h2 {
            font-size: 20px;
            color: #3d3d3d;
            word-break: break-all;
          }
          i {
            display: inline-block;
            @include size(40px, 20px);
            margin-left: 20px;
            background-color: #f9521f;
            border-radius: 4px;
            color: #fff;
            line-height: 20px;
            font-size: 12px;
            text-align: center;
            font-style: normal;
            flex-shrink: 0;
          }
          span {
            color: rgba($color: #3d3d3d, $alpha: 0.8);
            font-size: 14px;
          }
        }
        .box-right-area {
          color: #3d3d3d;
          flex-shrink: 0;
          margin-left: 15px;
          a {
            font-size: 14px;
            @include h-c(null, null, #3d3d3d, #f9521f);
            flex-shrink: 0;
            line-height: 30px;
          }
          .mg-r-14 {
            margin-right: 14px;
          }
          .share-icon {
            margin-left: 10px;
            @include size(20px);
            @include bg-setting;
          }
          .share1 {
            background-image: url("~@/assets/images/share1@2x.png");
          }
          .share2 {
            background-image: url("~@/assets/images/share2@2x.png");
          }
          .share3 {
            background-image: url("~@/assets/images/share3@2x.png");
          }
        }
      }

      .time-area {
        padding: 15px;
        background-color: #feede8;
        height: 84px;
        .name {
          font-style: 14px;
          font-weight: 600;
          margin-bottom: 6px;
          color: #3d3d3d;
          flex-shrink: 0;
        }
        .time {
          color: #f9521f;
          font-size: 18px;
          flex-shrink: 0;
        }
      }

      .check-area {
        margin: 20px 0 0 30px;
        color: #3d3d3d;

        span {
          @include h-c(null, null, #1c9cdf, rgba(#1c9cdf, 0.7));
          cursor: pointer;
        }
      }

      .submit-button {
        @include size(140px, 40px);
        @include btn-s(null, 40px, 5px);
        @include h-c(#f9521f, rgba(249, 82, 31, 0.8), #fff);
        margin: 36px auto 30px;
      }
      .flow-chart-title {
        font-size: 16px;
        color: #3d3d3d;
        font-weight: 600;
        text-align: center;
        margin-bottom: 30px;
      }
      .flow-name {
        font-size: 14px;
        color: rgba($color: #3d3d3d, $alpha: 0.8);
      }
      .long-arrow {
        @include size(300px, 20px);
        @include bg-setting("long-arrow");
        margin-bottom: 9px;
      }
      .flow-item {
        min-width: 50px;
        padding-top: 64px;
        font-size: 14px;
        font-weight: 600;
        text-align: center;
        @include bg-setting(null, 50px 50px, top center);
      }
      .arrow-item {
        width: 96px;
        padding-bottom: 9px;
        line-height: 25px;
        @include bg-setting(null, 56px 7px, bottom center);
        text-align: center;
        height: 30px;
      }
      .flow-item-strong {
        color: #f9521f;
      }
    }
    .bottom-box {
      margin-top: 15px;
      padding: 35px 0 50px;
    }
  }

  .right-area {
    width: 435px;
    background: #ffffff;
    border: 1px solid #eaeaea;
    padding: 20px 19px;

    p {
      font-size: 14px;
      color: rgba($color: #3d3d3d, $alpha: 0.8);
      line-height: 1.5;
      word-break: break-all;
      margin-top: 18px;
      transition: color 0.3s;
      &:hover {
        color: #f9521f;
      }
    }
  }
}
</style>
